@echo off
set logfile="%TMP%\srvlog.txt"
set flagfile="%TMP%\openconn.flg"

if exist %logfile% goto begin
echo [%date:~4,10% %time%] logfile created>%logfile%

:begin
echo -->>%logfile%
echo [%date:~4,10% %time%] srvnet check triggered>>%logfile%

if exist %flagfile% goto recent

openfiles /Query 2>NUL | FIND /C "INFO: No shared open files found" >NUL
if errorlevel 1 goto yes_opens
echo [%date:~4,10% %time%] no open files>>%logfile%

net session | find /C "There are no entries in the list" >NUL
if errorlevel 1 goto yes_opens
echo [%date:~4,10% %time%] no open sessions>>%logfile%

powercfg -requests | find /C "[DRIVER] \FileSystem\srvnet" >NUL
if errorlevel 1 goto no_srvnet_block

:block
echo [%date:~4,10% %time%] **block detected, restarting srv**>>%logfile%
net stop  /y srv >NUL 2>NUL
net start /y srv >NUL 2>NUL
goto :eof

:recent
echo [%date:~4,10% %time%] open files or sessions were detected on the last run, not restarting srv>>%logfile%
del %flagfile%
goto :eof

:yes_opens
echo [%date:~4,10% %time%] open files or sessions detected, not restarting srv>>%logfile%
echo [%date:~4,10% %time%] >%flagfile%
goto :eof

:no_srvnet_block
echo [%date:~4,10% %time%] no srvnet block detected, not restarting srv>>%logfile%
goto :eof